package com.mitgroup.dmrvs.view;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.mitgroup.dmrvs.R;
import com.mitgroup.dmrvs.adapter.SpinnerAdapter;
import com.mitgroup.dmrvs.utils.AppManager;
import com.mitgroup.dmrvs.utils.FileUtil;
import com.mitgroup.dmrvs.utils.Utils;
import com.mitgroup.dmrvs.webservice.WSClient;

import org.json.JSONTokener;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.PreferencesUtils;

public class ReceiveCarActivity extends AppCompatActivity {

    private static final int MSG_REGISTER_CAR = 1;
    private static final String BUNDLE_MSG_REGISTER_CAR_FAIL = "register_car_fail";
    private static final String BUNDLE_LOCAL_ERROR = "local_error";
    private static final String BUNDLE_MSG_REGISTER_CAR_JUMP = "register_car_jump";
    private static final int MSG_GET_CAR_INFO= 2;
    private static final String BUNDLE_MSG_GET_CAR_INFO = "get_car_info";
    private static final int REQUEST_CODE_LICENSE_PLATE = 122;
    private static final int REQUEST_CODE_GENERAL_BASIC = 106;
    private Intent intent;
    /**handler对象*/
    private Handler handler;
    private ProgressDialog progressDialog;
    @BindView(R.id.btn_back)
    public Button back;
    @OnClick(R.id.btn_back)
    public void onBack(View view) {
        this.finish();
    }
    @BindView(R.id.tv_user_name)
    public TextView tvUserName;
    @BindView(R.id.iv_quit)
    public Button quit;
    @OnClick(R.id.iv_quit)
    public void onQuit(View view) {
        Utils.Exit(this);
    }

    @BindView(R.id.btn_nav01)
    public Button btnReceiveCar;
    @BindView(R.id.btn_nav02)
    public Button btnDiagnose;
    @OnClick(R.id.btn_nav02)
    public void onDiagnose(View view) {
        intent = new Intent(ReceiveCarActivity.this,
                CarDiagnoseActivity.class);
        startActivity(intent);
    }
    @BindView(R.id.btn_nav03)
    public Button btnSettings;
    @OnClick(R.id.btn_nav03)
    public void onSettings(View view) {
        intent = new Intent(ReceiveCarActivity.this,
                SettingsActivity.class);
        startActivity(intent);
    }

    @BindView(R.id.et_receive_time)
    public EditText etReceiveTime;
    @BindView(R.id.et_plate_number)
    public EditText etPlateNumber;
    @BindView(R.id.et_car_vin)
    public EditText etCarVin;

    @BindView(R.id.et_car_brand)
    public EditText etCarBrand;
    @BindView(R.id.et_family_name)
    public EditText etFamilyName;
    @BindView( R.id.et_year_pattern)
    public EditText etYearPattern;
    @BindView(R.id.et_engine_desc)
    public EditText etEngineDesc;
    @BindView(R.id.et_gearbox_name)
    public EditText etGearboxName;
    @BindView(R.id.et_fuel_jet_type)
    public EditText etFuelJetType;
    @BindView(R.id.et_supply_oil)
    public EditText etSupplyOil;
    @BindView(R.id.sp_vehicle_name)
    public Spinner spVehicleName;
    @BindView( R.id.et_mileage)
    public EditText etMileage;
    @BindView(R.id.et_buy_car_time)
    public EditText etBuyCarTime;
    @OnClick({R.id.et_receive_time,R.id.et_buy_car_time})
    public void onGetDate(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = View.inflate(this, R.layout.date_dialog, null);
        final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
        builder.setView(view);

        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null);

        if (v.getId() == R.id.et_receive_time) {

            etReceiveTime.setSelection(etReceiveTime.getText().length());
            builder.setTitle("选取接车时间");
            builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {

                    StringBuffer sb = new StringBuffer();
                    sb.append(String.format("%d-%02d-%02d",
                            datePicker.getYear(),
                            datePicker.getMonth() + 1,
                            datePicker.getDayOfMonth()));
                    sb.append("  ");
                    etReceiveTime.setText(sb);
                    dialog.cancel();
                }
            });

        } else if (v.getId() == R.id.et_buy_car_time) {

            etBuyCarTime.setSelection(etBuyCarTime.getText().length());

            builder.setTitle("选取购车时间");
            builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {

                    StringBuffer sb = new StringBuffer();
                    sb.append(String.format("%d-%02d-%02d",
                            datePicker.getYear(),
                            datePicker.getMonth() + 1,
                            datePicker.getDayOfMonth()));
                    sb.append("  ");
                    etBuyCarTime.setText(sb);
                    dialog.cancel();
                }
            });
        }

        Dialog dialog = builder.create();
        dialog.show();
    }
    @BindView(R.id.btn_register_car)
    public Button btnRegisterCar;
    @OnClick(R.id.btn_register_car)
    public void onRegisterCar(View view) {
        String  receiveTimeStr=etReceiveTime.getText().toString();
        String plateNumbStr=etPlateNumber.getText().toString();
        String carBrandStr=etCarBrand.getText().toString();
        String mileageStr=etMileage.getText().toString();
        String  buyCarTimeStr=etBuyCarTime.getText().toString();
        String vinStr=etCarVin.getText().toString();
        String familyNameStr=etFamilyName.getText().toString();
        String yearPatternStr=etYearPattern.getText().toString();
        String engineDescStr=etEngineDesc.getText().toString();
        String gearboxNameStr=etGearboxName.getText().toString();
        String fuelJetTypeStr=etFuelJetType.getText().toString();
        String supplyOilStr=etSupplyOil.getText().toString();
        if("请选择".equals(vehicleNameStr))
        {
            vehicleNameStr="";
        }
        if (receiveTimeStr == null ||"".equals(receiveTimeStr))
        {
            Toast.makeText(getApplicationContext(), "接车时间不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }
        else if(plateNumbStr== null ||"".equals(plateNumbStr))
        {
            Toast.makeText(getApplicationContext(), "车牌号不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }
        else if(vinStr == null ||"".equals(vinStr))
        {
            Toast.makeText(getApplicationContext(), "VIN码不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }
        else if(carBrandStr == null ||"".equals(carBrandStr))
        {
            Toast.makeText(getApplicationContext(), "品牌名称不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }
        else if(mileageStr == null ||"".equals(mileageStr))
        {
            Toast.makeText(getApplicationContext(), "行驶里程不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }
        else if(buyCarTimeStr == null ||"".equals(buyCarTimeStr))
        {
            Toast.makeText(getApplicationContext(), "购车时间不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }
        else
        {
            if(!Utils.isCarNo(plateNumbStr))
            {
                Toast.makeText(getApplicationContext(), "车牌号输入格式不正确！", Toast.LENGTH_SHORT).show();
                return;
            }
            if(Utils.isNetworkAvailable(ReceiveCarActivity.this)==false)
            {
                Toast.makeText(getApplicationContext(), "网络尚未连接，请连接网络！", Toast.LENGTH_SHORT).show();
                return;
            }
            //public String  addCarInfo(String userId,String vin,String  brandName,String familyName,String yearPattern,String engineDesc,String gearboxName,String fuelJetType,String  inairform,String cfgLevel ,String plateNumber,String receiveCarDate,String buyCarDate,String mileage )
            //String password1=MD5.encrypt(password);
            final String []key={"userId","vin","carBrand","familyName","yearPattern","engineDesc","gearboxName","fuelJetType","supplyOil","vehicleName","plateNumber","receiveCarDate","buyCarDate","mileage"};
            final String []value={userId,vinStr,carBrandStr,familyNameStr,yearPatternStr,engineDescStr,gearboxNameStr,fuelJetTypeStr,supplyOilStr,vehicleNameStr,plateNumbStr,receiveTimeStr,buyCarTimeStr,mileageStr};
            progressDialog = ProgressDialog.show(ReceiveCarActivity.this,
                    getResources().getString(R.string.notice), "正在登记车辆信息...");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    String rs = "";
                    Bundle bundle = new Bundle();
                    try {
                        rs = WSClient.soapGetInfo("addCarInfo",key,value);
                        if(rs!=null &&!"".equals(rs))
                        {

                            JSONTokener jsonTokener = new JSONTokener(rs);
                            org.json.JSONObject  jsonObject = (org.json.JSONObject) jsonTokener
                                    .nextValue();
                            String status = jsonObject.getString("status");
                            String content = jsonObject.get("content").toString();
                            if("1".equals(status))
                            {
                                PreferencesUtils.putString(ReceiveCarActivity.this,"carInfoId", content);
                                bundle.putString(BUNDLE_MSG_REGISTER_CAR_JUMP, "车辆信息登记成功！");

                            }
                            else {

                                bundle.putString(BUNDLE_MSG_REGISTER_CAR_FAIL, "登记车辆信息失败，请重试！");
                            }
                        }
                        else
                        {
                            bundle.putString(BUNDLE_LOCAL_ERROR, "访问服务器失败！");
                        }

                    }
                    catch (Exception e) {
                        System.out.print(e.getMessage());
                        bundle.putString(BUNDLE_LOCAL_ERROR, "访问服务器失败！");
                    }
                    Message msg = myHandler.obtainMessage();
                    msg.what = MSG_REGISTER_CAR;
                    msg.setData(bundle);
                    myHandler.sendMessage(msg);
                }
            }).start();
        }
    }
    @BindView(R.id.btn_license_plate)
    public Button btnLicensePlate;
    @OnClick(R.id.btn_license_plate)
    public void onLicensePlate(View view) {
        if (!checkTokenStatus()) {
            return;
        }
        Intent intent = new Intent(ReceiveCarActivity.this, CameraActivity.class);
        intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                FileUtil.getSaveFile().getAbsolutePath());
        intent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                CameraActivity.CONTENT_TYPE_GENERAL);
        startActivityForResult(intent, REQUEST_CODE_LICENSE_PLATE);
    }
    @BindView(R.id.btn_vin)
    public Button btnVin;
    @OnClick(R.id.btn_vin)
    public void onVin(View view) {
        if (!checkTokenStatus()) {
            return;
        }
        String path =  FileUtil.getSaveFile( ).getAbsolutePath();
        Intent intent = new Intent(ReceiveCarActivity.this, CameraActivity.class);
        intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                path);
        intent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                CameraActivity.CONTENT_TYPE_GENERAL);
        startActivityForResult(intent, REQUEST_CODE_GENERAL_BASIC);

    }
    public String userId;
    private List<String> data_list;
    private SpinnerAdapter spinnerAdapter;
    private AlertDialog.Builder alertDialog;
    public String vehicleNameStr;
    private boolean hasGotToken = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receive_car);
        ButterKnife.bind(this);
        initView();
        initAccessTokenWithAkSk();
        File file = new File(Environment.getExternalStorageDirectory()+"/dmrvs/");
        FileUtil.deleteFile(file);
    }
    private void initView() {
        AppManager.getAppManager().addActivity(this);
         userId = PreferencesUtils.getString(ReceiveCarActivity.this, "userId");

        String userName=PreferencesUtils.getString(ReceiveCarActivity.this,"userName");
        tvUserName.setText(userName);
        etPlateNumber.setOnFocusChangeListener(new android.view.View.
                OnFocusChangeListener() {
            public void onFocusChange(View v,boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                } else {
                    etPlateNumber.setText(etPlateNumber.getText().toString().toUpperCase());
                }
            }
        });
        etCarVin.setOnFocusChangeListener(new android.view.View.
                OnFocusChangeListener() {
            public void onFocusChange(View v,boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                } else {
                    etCarVin.setText(etCarVin.getText().toString().toUpperCase());
                    getCarInfoByVin(etCarVin.getText().toString());
                }
            }
        });
         int inType = etReceiveTime.getInputType();
        etReceiveTime.setInputType(InputType.TYPE_NULL);
        etReceiveTime.setInputType(inType);
         inType = etBuyCarTime.getInputType();
        etBuyCarTime.setInputType(InputType.TYPE_NULL);
        etBuyCarTime.setInputType(inType);
        btnReceiveCar.setBackgroundResource(R.drawable.nav_icon01_active);
        //数据
        data_list = new ArrayList<String>();
        data_list.add("请选择");
        //适配器
        spinnerAdapter= new SpinnerAdapter(this,android.R.layout.simple_spinner_item, data_list);
        /* 设置样式 */
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spVehicleName.setAdapter(spinnerAdapter);
    }


    @Override
    protected void onResume() {
        super.onResume();
}

    private boolean checkTokenStatus() {
        if (!hasGotToken) {
            Toast.makeText(getApplicationContext(), "token还未成功获取", Toast.LENGTH_LONG).show();
        }
        return hasGotToken;
    }
    /**
     * 以license文件方式初始化
     */
    private void initAccessToken() {
        OCR.getInstance(this).initAccessToken(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken accessToken) {
                String token = accessToken.getAccessToken();
                hasGotToken = true;
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                alertText("licence方式获取token失败", error.getMessage());
            }
        }, getApplicationContext());
    }

    /**
     * 用明文ak，sk初始化
     */
    private void initAccessTokenWithAkSk() {
        OCR.getInstance(this).initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();
                hasGotToken = true;
            }
            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                alertText("AK，SK方式获取token失败", error.getMessage());
            }
        }, getApplicationContext(),  "6mbmnEVCj4cGG1x2YoFuaR7a", "YZlGWBozCVOAmneVpY7jaz4KvL0E4wpM");
    }

    /**
     * 自定义license的文件路径和文件名称，以license文件方式初始化
     */
    private void initAccessTokenLicenseFile() {
        OCR.getInstance(this).initAccessToken(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken accessToken) {
                String token = accessToken.getAccessToken();
                hasGotToken = true;
            }
            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                alertText("自定义文件路径licence方式获取token失败", error.getMessage());
            }
        }, "aip.license", getApplicationContext());
    }
    private void alertText(final String title, final String message) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                alertDialog.setTitle(title)
                        .setMessage(message)
                        .setPositiveButton("确定", null)
                        .show();
            }
        });
    }
    @Override
    public void onRequestPermissionsResult(int requestCode,  String[] permissions,int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            initAccessToken();
        } else {
            Toast.makeText(getApplicationContext(), "需要android.permission.READ_PHONE_STATE", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 识别成功回调，车牌识别
        if (requestCode == REQUEST_CODE_LICENSE_PLATE && resultCode == Activity.RESULT_OK) {
            String filePath= FileUtil.getSaveFile().getAbsolutePath();
            RecognizeService.recLicensePlate(this,filePath,
                    new RecognizeService.ServiceListener() {
                        @Override
                        public void onResult(String result) {
                            try {
                                JSONObject obj = JSONObject.parseObject(result);
                                JSONObject infoObj = obj.getJSONObject("words_result");
                                String plateNumber = infoObj.getString("number");
                                if(plateNumber!=null&&!" ".equals(plateNumber)){
                                    etPlateNumber.setText(plateNumber);
                                }

                            }
                            catch (Exception ex){
                                Toast.makeText(getApplicationContext(), "车牌号识别失败，请重试！", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        }
        // 识别成功回调，通用文字识别
        if (requestCode == REQUEST_CODE_GENERAL_BASIC && resultCode == Activity.RESULT_OK) {

            RecognizeService.recGeneralBasic(this, FileUtil.getSaveFile().getAbsolutePath(),
                    new RecognizeService.ServiceListener() {
                        @Override
                        public void onResult(String result) {
                            try {
                                JSONObject obj = JSONObject.parseObject(result);
                                JSONArray infoObj = obj.getJSONArray("words_result");
                                JSONObject word = (JSONObject)JSONObject.toJSON(infoObj.get(0));
                                 String vinStr = word.getString("words");
                                if(vinStr!=null&& !" ".equals(vinStr))
                                {
                                    etCarVin.setText(vinStr);
                                    getCarInfoByVin(vinStr);
                                }


                            }catch (Exception e){
                                Toast.makeText(getApplicationContext(), "车辆VIN识别失败，请重试！", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        }

    }
    private Handler myHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            switch (msg.what) {
                case MSG_REGISTER_CAR:
                    String key = msg.getData().keySet().iterator().next();
                    if (BUNDLE_MSG_REGISTER_CAR_FAIL.equals(key)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        Toast.makeText(getApplicationContext(),msg.getData().getString( BUNDLE_MSG_REGISTER_CAR_FAIL), Toast.LENGTH_SHORT).show();

                    }
                    else if (msg.getData().keySet().contains(BUNDLE_MSG_REGISTER_CAR_JUMP)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }

                        Toast.makeText(getApplicationContext(), msg.getData().getString(BUNDLE_MSG_REGISTER_CAR_JUMP), Toast.LENGTH_SHORT).show();
                        ReceiveCarActivity.this.finish();
                        intent = new Intent(ReceiveCarActivity.this,
                                CarDiagnoseActivity.class);
                        startActivity(intent);

                    }
                    else if (BUNDLE_LOCAL_ERROR.equals(key)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        Toast.makeText(getApplicationContext(), "服务器连接失败！请重试！", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case MSG_GET_CAR_INFO:
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                        progressDialog = null;
                    }
                    String content=msg.getData().getString(BUNDLE_MSG_GET_CAR_INFO);
                    if(!"".equals(content))
                    {

                        try {
                            String[] contentArr= content.split(",");
                            String tempStr="";
                            for(int i=0;i<contentArr.length;i++)
                            {
                                tempStr=contentArr[i];
                                String[] tempStrArr=tempStr.split(":");
                                if("vin".equals(tempStrArr[0]))
                                {
                                    if(tempStrArr.length==2)
                                    {
                                        etCarVin.setText(tempStrArr[1]);
                                    }
                                }
                                else if("brandName".equals(tempStrArr[0]))
                                {
                                    if(tempStrArr.length==2)
                                    {
                                        etCarBrand.setText(tempStrArr[1]);
                                    }
                                }
                                else if("familyName".equals(tempStrArr[0]))
                                {
                                    if(tempStrArr.length==2)
                                    {
                                        etFamilyName.setText(tempStrArr[1]);
                                    }
                                }
                                else if("engineDesc".equals(tempStrArr[0]))
                                {
                                    if(tempStrArr.length==2)
                                    {
                                        etEngineDesc.setText(tempStrArr[1]);
                                    }
                                }
                                else if("yearPattern".equals(tempStrArr[0]))
                                {
                                    if(tempStrArr.length==2)
                                    {
                                        etYearPattern.setText(tempStrArr[1]);
                                    }
                                }
                                else if("gearboxName".equals(tempStrArr[0]))
                                {
                                    if(tempStrArr.length==2)
                                    {
                                        etGearboxName.setText(tempStrArr[1]);
                                    }
                                }
                                else if("fuelJetType".equals(tempStrArr[0]))
                                {
                                    if(tempStrArr.length==2)
                                    {
                                        etFuelJetType.setText(tempStrArr[1]);
                                    }
                                }
                                else if("supplyOil".equals(tempStrArr[0]))
                                {
                                    if(tempStrArr.length==2)
                                    {
                                        etSupplyOil.setText(tempStrArr[1]);
                                    }
                                }
                                else if("vehicleName".equals(tempStrArr[0]))
                                {
                                    if(tempStrArr.length==2)
                                    {
                                        String cftLevelStr=tempStrArr[1];
                                        data_list = new ArrayList<String>();
                                        data_list.add("请选择");
                                        if(cftLevelStr.indexOf("|")>-1)
                                        {
                                            String []cftLevelArr=cftLevelStr.split("\\|");
                                            for(int f=0;f<cftLevelArr.length;f++){
                                                data_list.add(cftLevelArr[f].trim());
                                            }

                                        }
                                        else {
                                            data_list.add(cftLevelStr);
                                        }
                                        //适配器
                                        spinnerAdapter= new SpinnerAdapter(ReceiveCarActivity.this,android.R.layout.simple_spinner_item, data_list);
                                        //设置样式
                                        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                                        //加载适配器
                                        spVehicleName.setAdapter(spinnerAdapter);
                                        spVehicleName.setOnItemSelectedListener(new SpinnerSelectedListener());
                                    }
                                }
                            }
                        } catch (Exception e) {
                            String ex=e.getMessage();
                            // TODO: handle exception
                        }

                    }
                    break;

                default:
                    break;
            }
            removeMessages(msg.what);

        }
    };
    protected void getCarInfoByVin(String vinStr)
    {

        if(Utils.isNetworkAvailable(ReceiveCarActivity.this)==false)
        {
            Toast.makeText(this, "网络尚未连接，请连接网络！", Toast.LENGTH_SHORT).show();
            return;
        }
        final String []key={"vinStr"};
        final String []value={vinStr};
        progressDialog = ProgressDialog.show(ReceiveCarActivity.this,
                getResources().getString(R.string.notice), "正在获取车辆基本信息...");
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bundle bundle = new Bundle();
                try {
                    String rs = WSClient.soapGetInfo("getCarInfoByVin",key,value);
                    JSONTokener jsonTokener = new JSONTokener(rs);
                    org.json.JSONObject  jsonObject = (org.json.JSONObject) jsonTokener.nextValue();
                    String status = jsonObject.getString("status");
                    String content = jsonObject.get("content").toString();
                    if("1".equals(status)){
                        bundle.putString(BUNDLE_MSG_GET_CAR_INFO, content);
                    }

                }
                catch (Exception e) {
                   String ex=e.getMessage();

                }
                Message msg = myHandler.obtainMessage();
                msg.what = MSG_GET_CAR_INFO;
                msg.setData(bundle);
                myHandler.sendMessage(msg);
            }
        }).start();
    }
    //使用数组形式操作
    class SpinnerSelectedListener implements AdapterView.OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                                   long arg3) {
            vehicleNameStr=data_list.get(arg2);
        }

        public void onNothingSelected(AdapterView<?> arg0) {
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放内存资源
        OCR.getInstance(this).release();
        AppManager.getAppManager().finishActivity(this);
    }
}
